package com.elong.businesstravel.modules.member;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.Base64;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.core.ImageLoader;
import com.android.support.jhf.universalimageloader.core.imageaware.ImageViewAware;
import com.android.support.jhf.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.android.support.jhf.utils.Base64Util;
import com.android.support.jhf.utils.ImageUtil;
import com.android.support.jhf.utils.ThumbnailUtils;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.uploadpic.UploadPic;
import com.elong.businesstravel.base.uploadpic.UploadPic.OnGetPicSucceed;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.protocol.login.MemberAddcltCardRequest;
import com.elong.businesstravel.protocol.login.MemberAddcltCardResponse;

/**
 * 名片验证
 * 
 * @author lenovo
 * 
 */
public class CardAuthenticateActivity extends BaseActivity {

	public static final int IMAGE_BOUND = 512;

	private ImageView mCardImageView;
	private Button cameraButton;
	private Button submitButton;

	private UploadPic mUploadPic;
	
	private String mPicPathString;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_card_authenticate);

		init();
	}

	@Override
	protected void init() {

		mUploadPic = new UploadPic(this);

		mCardImageView = (ImageView) findViewById(R.id.cardImageView);

		setListener();
		setTitleNavBar();
	}

	@Override
	protected void setListener() {
		cameraButton = (Button) findViewById(R.id.cameraButton);
		cameraButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
//				mUploadPic.doTakePhotoCrop();
				mUploadPic.doTakePhoto();
			}
		});
		submitButton = (Button)findViewById(R.id.submitButton);
		submitButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				uploadPic(mPicPathString);
			}
		});

		mUploadPic.setOnGetPicSucceed(new OnGetPicSucceed() {

			@Override
			public void onGetPicSucceed(String picPathString) {
//				uploadPic(picPathString);
				mPicPathString = picPathString;
				picSucceed(picPathString);
			}
		});
	}

	private void picSucceed(final String picPathString) {
		
		ImageLoader.getInstance().displayImage(
				Uri.fromFile(
						new File(picPathString))
						.toString(),
				new ImageViewAware(mCardImageView),
				mApplication.mDisplayImageOptions,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(
							String imageUri,
							View view,
							Bitmap loadedImage) {
						int degree = ImageUtil.readPictureDegree(picPathString);
						DebugLog.logI("degree : " + degree);
						Bitmap tempBitmap = loadedImage;
						if(Math.abs(degree) > 0){
							tempBitmap = ImageUtil.rotaingImageView(degree, tempBitmap);
						}
						mCardImageView
								.setImageBitmap(tempBitmap);
						submitButton.setVisibility(View.VISIBLE);
						cameraButton.setVisibility(View.GONE);
					}
				});
	}
	
	@Override
	protected void setTitleNavBar() {
		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage("名片验证");
		titleNavBarView.setLeftDrawableImage(R.drawable.btn_title_back);
		titleNavBarView.setLeftButtonImageString(0, "返回", R.color.text_blue);
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
	}

	private void uploadPic(final String picPathString) {
		showWaitDialog("正在上传请稍后...", new OnKeyCancel() {

			@Override
			public void onKeyCancelListener() {
				NetworkClient.getNetworkClient().cancelRequests(mContext, true);
			}
		});
		String datePicString = getPicString(picPathString);
		if (null == datePicString) {
			return;
		}
		NetworkClient.getNetworkClient().PostRequest(
				new MemberAddcltCardRequest(mContext, datePicString),
				new MemberAddcltCardResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								if ("0".equals(status)) {
									
									HandlerToastUI.getHandlerToastUI(mContext,
											"上传成功");
								} else {
									if (!TextUtils.isEmpty(messageString)) {
										HandlerToastUI.getHandlerToastUI(
												mContext, messageString);
									}
								}
								hideWaitDialog();
								setResult(RESULT_OK);
								finish();
							}
						});

					}
				}, null, new BaseErrorListener() {
					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						if (null != mContext && mContext instanceof Activity) {
							StringBuffer stringBuffer = new StringBuffer();
							ErrorExceptionHandler.NetworkExceptionHandler(
									stringBuffer, error);
							if (!TextUtils.isEmpty(stringBuffer.toString())) {
								HandlerToastUI.getHandlerToastUI(mContext,
										stringBuffer.toString());
							}

						}
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								hideWaitDialog();
							}
						});
					}

				});
	}

	private String getPicString(String picPathString) {
		String datePicString = null;
		try {
			int[] imageBounds = ImageUtil
					.getImageBounds(new File(picPathString));
			DebugLog.logI("imageBounds : " + imageBounds[0]);
			Bitmap bitmap = null;
			if (imageBounds[0] > IMAGE_BOUND) {
				bitmap = ThumbnailUtils.setThumbnailBitmap(new File(
						picPathString), IMAGE_BOUND, IMAGE_BOUND);
			} else {
				bitmap = BitmapFactory.decodeFile(picPathString);
			}

			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.JPEG, 100, byteArrayOutputStream);

			datePicString = Base64Util.encode(byteArrayOutputStream
					.toByteArray());

			DebugLog.logI("datePicString : " + datePicString.length());
			DebugLog.logI("byteArrayOutputStream : "
					+ byteArrayOutputStream.toByteArray().length);
			byteArrayOutputStream.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return datePicString;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null != mUploadPic) {
			mUploadPic.onActivityResult(requestCode, resultCode, data);
		}
	}

}
